package com.lemon.smartsafetynew.ui.activity.hidden;

import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafetynew.entity.common.DateTypeEnum;
import com.lemon.smartsafetynew.entity.event.common.DataEvent;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenBo;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenSourceVo;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenStatusVo;
import com.lemon.smartsafetynew.entity.me.MeCompanyVo;
import com.lemon.smartsafetynew.entity.record.GridInfoDo;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafetynew.ui.adapter.hidden.SafeHiddenDangerSourceAdapter;
import com.lemon.smartsafetynew.ui.adapter.hidden.SafeHiddenDangerStatusAdapter;
import com.lemon.smartsafetynew.ui.fragment.hidden.SafeHiddenListFragmentNew;
import com.lemon.smartsafetynew.ui.fragment.record.CompanyListFragment;
import com.lemon.smartsafetynew.ui.fragment.record.GridListFragment;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.lemon.smartsafetynew.util.user.UserTypeUtil;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 功能描述：隐患查报新首页
 */
public class SafeHiddenDangerHomeNewActivity extends SwipeBackActivity {

    @Bind(R.id.hidden_status_tv)
    TextView hiddenStatusTv;
    @Bind(R.id.hidden_status_arrow)
    ImageView hiddenStatusArrow;
    @Bind(R.id.hidden_status_layout)
    RelativeLayout hiddenStatusLayout;
    @Bind(R.id.hidden_status_rl)
    RelativeLayout hiddenStatusRl;

    @Bind(R.id.hidden_source_tv)
    TextView hiddenSourceTv;
    @Bind(R.id.hidden_source_arrow)
    ImageView hiddenSourceArrow;
    @Bind(R.id.hidden_source_layout)
    RelativeLayout hiddenSourceLayout;
    @Bind(R.id.hidden_source_rl)
    RelativeLayout hiddenSourceRl;

    @Bind(R.id.time_tv)
    TextView timeTv;
    @Bind(R.id.time_arrow)
    ImageView timeArrow;
    @Bind(R.id.time_layout)
    RelativeLayout timeLayout;
    @Bind(R.id.time_rl)
    RelativeLayout timeRl;

    @Bind(R.id.frameLayout)
    FrameLayout frameLayout;
    @Bind(R.id.gray_layout)
    View grayLayout;
    @Bind(R.id.filterBar)
    LinearLayout filterBar;

    @Bind(R.id.editText)
    TextView editText;

    @Bind(R.id.search_layout)
    RelativeLayout searchLayout;

    // ==================== View ====================
    private SafeHiddenListFragmentNew safeHiddenListFragmentNew;

    // ==================== Data ====================
    private List<SafeHiddenStatusVo> statusVos;
    private List<SafeHiddenSourceVo> sourceVos;
    private String status = "";
    private String source = "";
    private String startTime = "";
    private String endTime = "";
    private String companyId = "";
    private String gridId = "";


    @Override
    protected void initTitle() {
        this.setBarTitle("");
    }
    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(SafeHiddenDangerHomeNewActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_hidden_danger_home_new;
    }

    @Override
    protected void initViews() {
        super.initViews();

        if (!UserTypeUtil.isGovType(AccountUtil.getUserType())) {
            //企业人员隐藏搜网格和搜企业
            searchLayout.setVisibility(View.GONE);
            if (mMainTitle != null) {
                mMainTitle.setVisibility(View.VISIBLE);
            }
            setBarTitle(R.string.work_options_main_2);
        } else {
            //政府人员显示搜网格和搜企业
            if (mMainTitle != null) {
                mMainTitle.setVisibility(View.GONE);
            }
            searchLayout.setVisibility(View.VISIBLE);
        }

        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initFragment();
    }

    private void initData() {

        statusVos = new ArrayList<>();
        sourceVos = new ArrayList<>();

        //初始化隐患状态列
        statusVos.add(new SafeHiddenStatusVo("全部", "", true));
        statusVos.add(new SafeHiddenStatusVo("待整改", SafeHiddenBo.Status.rectify.getValue(), false));
        statusVos.add(new SafeHiddenStatusVo("待复查", SafeHiddenBo.Status.review.getValue(), false));
        statusVos.add(new SafeHiddenStatusVo("已关闭", SafeHiddenBo.Status.finish.getValue(), false));
        statusVos.add(new SafeHiddenStatusVo("超期未整改", SafeHiddenBo.Status.overtime_rectify.getValue(), false));

        //初始化隐患来源列
        sourceVos.add(new SafeHiddenSourceVo("全部", "", true));
        sourceVos.add(new SafeHiddenSourceVo("随手拍", SafeHiddenBo.SourceType.random_photo.getValue(), false));
        sourceVos.add(new SafeHiddenSourceVo("风险点上报", SafeHiddenBo.SourceType.from_self_check_point.getValue(), false));
        sourceVos.add(new SafeHiddenSourceVo("网格点上报", SafeHiddenBo.SourceType.from_grid_point.getValue(), false));

    }

    /**
     * 刷新隐患列表Fragment
     */
    private void initFragment() {

        if ("".equals(startTime) || "".equals(endTime)) {
            safeHiddenListFragmentNew = SafeHiddenListFragmentNew.newInstance(status, source,
                    null, null, companyId, gridId);
        } else {
            safeHiddenListFragmentNew = SafeHiddenListFragmentNew.newInstance(status, source,
                    startTime, endTime, companyId, gridId);
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, safeHiddenListFragmentNew).commit();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataEvent(DataEvent event) {
        if (CompanyListFragment.class.getName().equals(event.getTag())) {
            MeCompanyVo meCompanyVo = (MeCompanyVo) event.getData();
            editText.setText(meCompanyVo.getCompany_name());

            companyId = meCompanyVo.getCompany_id();
            gridId = "";

        } else if (GridListFragment.class.getName().equals(event.getTag())) {
            GridInfoDo gridInfoDo = (GridInfoDo) event.getData();
            editText.setText(gridInfoDo.getGrid_name());

            gridId = gridInfoDo.getGrid_id();
            companyId = "";
        }
    }

    private int currentId = R.id.gray_layout; // 这里currentId只要不是 R.id.hidden_status_layout, R.id.hidden_source_layout, R.id.time_layout就可以

    @OnClick({R.id.hidden_status_layout, R.id.hidden_source_layout, R.id.time_layout, R.id.gray_layout, R.id.search_layout, R.id.clear_tv})
    public void onViewClicked(View view) {

        switch (view.getId()) {
            case R.id.hidden_status_layout:

                if (mPopupWindowHiddenStatus == null || !mPopupWindowHiddenStatus.isShowing()) {
                    disSelected(currentId);
                    currentId = R.id.hidden_status_layout;
                    select(currentId);
                } else {
                    disSelected(currentId);
                    currentId = R.id.gray_layout;
                }

                break;
            case R.id.hidden_source_layout:

                if (mPopupWindowHiddenSource == null || !mPopupWindowHiddenSource.isShowing()) {
                    disSelected(currentId);
                    currentId = R.id.hidden_source_layout;
                    select(currentId);
                } else {
                    disSelected(currentId);
                    currentId = R.id.gray_layout;
                }

                break;
            case R.id.time_layout:
                if (mPopupWindowTime == null || !mPopupWindowTime.isShowing()) {
                    disSelected(currentId);
                    currentId = R.id.time_layout;
                    select(currentId);
                } else {
                    disSelected(currentId);
                    currentId = R.id.gray_layout;
                }

                break;
            case R.id.gray_layout:

                disSelected(currentId);
                currentId = R.id.gray_layout;
                grayLayout.setVisibility(View.GONE);
                dismissPopWindow();

                break;
            case R.id.search_layout:
                UIHelper.showActivity(SafeHiddenDangerHomeNewActivity.this, SafeHiddenDangerSearchActivity.class);
                break;

            case R.id.clear_tv:
                //清空网格或者企业筛选条件
                editText.setText("");
                editText.setHint("搜网格￤搜企业");
                gridId = "";
                companyId = "";

                initFragment();
                break;
        }
    }


    private void disSelected(int id) {
        switch (id) {
            case R.id.hidden_status_layout:
                hiddenStatusArrow.setSelected(false);
                hiddenStatusLayout.setSelected(false);

                if ("".equals(status)) {
                    //当隐患状态没有过滤条件时
                    hiddenStatusTv.setSelected(false);
                    hiddenStatusRl.setSelected(false);
                } else {
                    hiddenStatusRl.setSelected(true);
                }

                if (mPopupWindowHiddenStatus != null) {
                    mPopupWindowHiddenStatus.dismiss();
                    mPopupWindowHiddenStatus = null;
                }

                break;
            case R.id.hidden_source_layout:

                hiddenSourceArrow.setSelected(false);
                hiddenSourceLayout.setSelected(false);

                if ("".equals(source)) {
                    //当隐患状态没有过滤条件时
                    hiddenSourceTv.setSelected(false);
                    hiddenSourceRl.setSelected(false);
                } else {
                    hiddenSourceRl.setSelected(true);
                }

                if (mPopupWindowHiddenSource != null) {
                    mPopupWindowHiddenSource.dismiss();
                    mPopupWindowHiddenSource = null;
                }
                break;
            case R.id.time_layout:

                timeArrow.setSelected(false);
                timeLayout.setSelected(false);

                if ("".equals(startTime) && "".equals(endTime)) {
                    //当时间端没有过滤条件时
                    timeTv.setSelected(false);
                    timeRl.setSelected(false);
                } else {
                    timeRl.setSelected(true);
                }

                if (mPopupWindowTime != null) {
                    mPopupWindowTime.dismiss();
                    mPopupWindowTime = null;
                }
                break;
        }
    }

    private void select(int id) {
        switch (id) {
            case R.id.hidden_status_layout:
                hiddenStatusTv.setSelected(true);
                hiddenStatusArrow.setSelected(true);
                hiddenStatusLayout.setSelected(true);
                popHiddenStatusWindow();
                break;
            case R.id.hidden_source_layout:
                hiddenSourceTv.setSelected(true);
                hiddenSourceArrow.setSelected(true);
                hiddenSourceLayout.setSelected(true);
                popHiddenSourceWindow();
                break;
            case R.id.time_layout:
                timeTv.setSelected(true);
                timeArrow.setSelected(true);
                timeLayout.setSelected(true);
                popHiddenTimeWindow();
                break;
        }
    }

    /**
     * popWindow消失
     */
    private void dismiss() {
        disSelected(currentId);
        currentId = R.id.gray_layout;
        grayLayout.setVisibility(View.GONE);
        dismissPopWindow();
    }

    /**
     * 隐患状态popWindow
     */
    private PopupWindow mPopupWindowHiddenStatus = null;

    private void popHiddenStatusWindow() {

        View contentView = LayoutInflater.from(SafeHiddenDangerHomeNewActivity.this).inflate(R.layout.layout_popup_window_recyclerview, null);

        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        SafeHiddenDangerStatusAdapter mAdapter = new SafeHiddenDangerStatusAdapter(SafeHiddenDangerHomeNewActivity.this, statusVos);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new SafeHiddenDangerStatusAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                status = statusVos.get(position).getStatus();
                if (position != 0) {
                    hiddenStatusTv.setText(statusVos.get(position).getStatusName());
                } else {
                    hiddenStatusTv.setText(getString(R.string.safe_hidden_danger_status_str));
                }

                for (int i = 0; i < statusVos.size(); i++) {
                    SafeHiddenStatusVo item = statusVos.get(i);
                    if (i == position) {
                        item.setSelected(true);
                    } else {
                        item.setSelected(false);
                    }
                    statusVos.set(i, item);
                }
                initFragment();
                dismiss();
            }
        });

        mPopupWindowHiddenStatus = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindowHiddenStatus.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方不会消失
        mPopupWindowHiddenStatus.setOutsideTouchable(false);
        mPopupWindowHiddenStatus.setFocusable(false);
        grayLayout.setVisibility(View.VISIBLE);

        mPopupWindowHiddenStatus.showAsDropDown(filterBar, 0, 0);

        mPopupWindowHiddenStatus.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (grayLayout != null) {
                    grayLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * 隐患来源
     */
    private PopupWindow mPopupWindowHiddenSource = null;

    private void popHiddenSourceWindow() {

        View contentView = LayoutInflater.from(SafeHiddenDangerHomeNewActivity.this).inflate(R.layout.layout_popup_window_recyclerview, null);

        RecyclerView recyclerView = (RecyclerView) contentView.findViewById(R.id.recyclerView);
        // 设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        SafeHiddenDangerSourceAdapter mAdapter = new SafeHiddenDangerSourceAdapter(SafeHiddenDangerHomeNewActivity.this, sourceVos);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setItemClickListener(new SafeHiddenDangerSourceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                source = sourceVos.get(position).getStatus();
                if (position != 0) {
                    hiddenSourceTv.setText(sourceVos.get(position).getStatusName());
                } else {
                    hiddenSourceTv.setText(getString(R.string.safe_hidden_danger_source_str));
                }
                for (int i = 0; i < sourceVos.size(); i++) {
                    SafeHiddenSourceVo item = sourceVos.get(i);
                    if (i == position) {
                        item.setSelected(true);
                    } else {
                        item.setSelected(false);
                    }
                    sourceVos.set(i, item);
                }
                initFragment();
                dismiss();
            }
        });

        mPopupWindowHiddenSource = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindowHiddenSource.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方不会消失
        mPopupWindowHiddenSource.setOutsideTouchable(false);
        mPopupWindowHiddenSource.setFocusable(false);
        grayLayout.setVisibility(View.VISIBLE);

        mPopupWindowHiddenSource.showAsDropDown(filterBar, 0, 0);

        mPopupWindowHiddenSource.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (grayLayout != null) {
                    grayLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * 隐患时间段
     */

    public enum Status {

        NONE("", "没被选中"),
        START("0", "开始时间被选中"),
        END("1", "结束时间被选中");

        private String value;
        private String desc;

        Status(String value, String desc) {
            this.value = value;
            this.desc = desc;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public String getDesc() {
            return desc;
        }

        public void setDesc(String desc) {
            this.desc = desc;
        }

    }

    private String isStartTime = Status.NONE.getValue();
    private PopupWindow mPopupWindowTime = null;

    private void popHiddenTimeWindow() {

        isStartTime = "";

        View contentView = LayoutInflater.from(SafeHiddenDangerHomeNewActivity.this).inflate(R.layout.layout_safe_hidden_time_pick_pop_window, null);

        final Button okBtn = (Button) contentView.findViewById(R.id.ok_btn);
        Button resetBtn = (Button) contentView.findViewById(R.id.reset_btn);
        final MaterialEditText startTimeEdit = (MaterialEditText) contentView.findViewById(R.id.start_time_et);
        final MaterialEditText endTimeEdit = (MaterialEditText) contentView.findViewById(R.id.end_time_et);
        final DatePicker datePicker = (DatePicker) contentView.findViewById(R.id.date_picker);

        startTimeEdit.setText(CommonUtil.avoidNullString(startTime, ""));
        endTimeEdit.setText(CommonUtil.avoidNullString(endTime, ""));

        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        int year = calendar.get(Calendar.YEAR);
        int monthOfYear = calendar.get(Calendar.MONTH);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        datePicker.setMaxDate(calendar.getTimeInMillis());  //设置最大日期为当日日期

        final long maxDate = datePicker.getMaxDate();
        final long minDate = datePicker.getMinDate();

        datePicker.init(year, monthOfYear, dayOfMonth, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                Calendar mCalendar = Calendar.getInstance();
                mCalendar.set(Calendar.YEAR, year);
                mCalendar.set(Calendar.MONTH, monthOfYear);
                mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                if (Status.START.getValue().equals(isStartTime)) {
                    startTimeEdit.setText(CommonUtil.dateToTimeStr(mCalendar.getTime(), DateTypeEnum.DAY));
                } else if (Status.END.getValue().equals(isStartTime)) {
                    endTimeEdit.setText(CommonUtil.dateToTimeStr(mCalendar.getTime(), DateTypeEnum.DAY));
                }

            }
        });

        startTimeEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTimeEdit.setFocusable(true);//设置输入框可聚集
                startTimeEdit.setFocusableInTouchMode(true);//设置触摸聚焦
                startTimeEdit.requestFocus();//请求焦点
                startTimeEdit.findFocus();//获取焦点
            }
        });

        endTimeEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endTimeEdit.setFocusable(true);//设置输入框可聚集
                endTimeEdit.setFocusableInTouchMode(true);//设置触摸聚焦
                endTimeEdit.requestFocus();//请求焦点
                endTimeEdit.findFocus();//获取焦点
            }
        });

        startTimeEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    isStartTime = Status.START.getValue();
                    if (!"".equals(startTimeEdit.getText().toString().trim())) { //当开始时间不为空时，设置date
                        Date date = CommonUtil.timeStrToDate(startTimeEdit.getText().toString().trim(), DateTypeEnum.DAY);
                        Calendar calendar2 = Calendar.getInstance();
                        calendar2.setTime(date);
                        datePicker.updateDate(calendar2.get(Calendar.YEAR), calendar2.get(Calendar.MONTH), calendar2.get(Calendar.DAY_OF_MONTH));
                    }

                    if ("".equals(endTimeEdit.getText().toString().trim())) {
                        datePicker.setMinDate(minDate);
                        datePicker.setMaxDate(maxDate);
                    } else {
                        datePicker.setMinDate(minDate);
                        datePicker.setMaxDate(CommonUtil.timeStrToDate(endTimeEdit.getText().toString().trim(), DateTypeEnum.DAY).getTime());
                    }

                }
            }
        });

        endTimeEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    isStartTime = Status.END.getValue();

                    if (!"".equals(endTimeEdit.getText().toString().trim())) {
                        Date date = CommonUtil.timeStrToDate(endTimeEdit.getText().toString().trim(), DateTypeEnum.DAY);
                        Calendar calendar1 = Calendar.getInstance();
                        calendar1.setTime(date);
                        datePicker.updateDate(calendar1.get(Calendar.YEAR), calendar1.get(Calendar.MONTH), calendar1.get(Calendar.DAY_OF_MONTH));
                    }

                    if ("".equals(startTimeEdit.getText().toString().trim())) {
                        datePicker.setMinDate(minDate);
                        datePicker.setMaxDate(maxDate);
                    } else {
                        datePicker.setMaxDate(maxDate);
                        datePicker.setMinDate(CommonUtil.timeStrToDate(startTimeEdit.getText().toString().trim(), DateTypeEnum.DAY).getTime());
                    }

                }
            }
        });

        startTimeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"".equals(startTimeEdit.getText().toString().trim())
                        && !"".equals(endTimeEdit.getText().toString().trim())) {
                    okBtn.setEnabled(true);
                } else {
                    okBtn.setEnabled(false);
                }
            }
        });

        endTimeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!"".equals(startTimeEdit.getText().toString().trim())
                        && !"".equals(endTimeEdit.getText().toString().trim())) {
                    okBtn.setEnabled(true);
                } else {
                    okBtn.setEnabled(false);
                }
            }
        });

        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTime = startTimeEdit.getText().toString().trim();
                endTime = endTimeEdit.getText().toString().trim();

                timeTv.setText(startTime + "至" + endTime);

                initFragment();
                dismiss();
            }
        });

        resetBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // ====== 取消焦点 =======
                endTimeEdit.setFocusable(false);
                endTimeEdit.setFocusableInTouchMode(false);
                startTimeEdit.setFocusable(false);
                startTimeEdit.setFocusableInTouchMode(false);

                datePicker.setMaxDate(maxDate);
                datePicker.setMinDate(minDate);

                startTime = "";
                endTime = "";
                startTimeEdit.setText(startTime);
                endTimeEdit.setText(endTime);
                timeTv.setText(getString(R.string.safe_hidden_danger_time_quantum_str));

                initFragment();
                dismiss();
            }
        });

        mPopupWindowTime = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindowTime.setBackgroundDrawable(new BitmapDrawable());
        //将这两个属性设置为false，使点击popupwindow外面其他地方不会消失
        mPopupWindowTime.setOutsideTouchable(false);
        mPopupWindowTime.setFocusable(false);
        grayLayout.setVisibility(View.VISIBLE);

        mPopupWindowTime.showAsDropDown(filterBar, 0, 0);

        mPopupWindowTime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (grayLayout != null) {
                    grayLayout.setVisibility(View.GONE);
                }
            }
        });

    }

    /**
     * 清除popWindow
     */
    private void dismissPopWindow() {
        if (mPopupWindowHiddenStatus != null) {
            mPopupWindowHiddenStatus.dismiss();
            mPopupWindowHiddenStatus = null;
        }

        if (mPopupWindowHiddenSource != null) {
            mPopupWindowHiddenSource.dismiss();
            mPopupWindowHiddenSource = null;
        }

        if (mPopupWindowTime != null) {
            mPopupWindowTime.dismiss();
            mPopupWindowTime = null;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        dismissPopWindow();
    }

}
